package util

import (
	"context"
	"encoding/json"
	"log/slog"
	"rule/cache"
	"rule/data"
	"rule/pkg/gwprop"
	"strconv"
)

var ctx = context.Background()

const (
	RuleEngineData string = "rule.engine.data"
)

func CloseRedis() {
	_ = cache.Rdb0.Close()
}

func SubscribeRedis() {
	go subscribeRedis()
}

func subscribeRedis() {
	macMq := gwprop.GetProp().Channel
	//
	pubSub := cache.Rdb0.Subscribe(ctx, macMq, RuleEngineData)

	//defer func() {
	//	_ = pubSub.Close()
	//}()
	_ch := pubSub.Channel()

	go ParseRedisMsg()
	go ParseFilterData()

	for raw := range _ch {
		if raw.Channel == macMq {
			slog.Debug("device_data", "payload", raw.Payload)
			redisMqMsg <- raw.Payload
		} else if raw.Channel == RuleEngineData {
			//
			dr := new(data.MyDataReport)
			err := json.Unmarshal([]byte(raw.Payload), dr)
			if err != nil {
				slog.Error("json.Unmarshal MyDataReport err", "error", err.Error())
				continue
			}
			time_ms, _ := strconv.ParseInt(dr.Ts, 10, 64)
			if time_ms <= 0 {
				slog.Error("time_ms err", "error", "接收到json的报文时间戳不对")
				continue
			}
			dr.Tint = time_ms
			redisMqData <- dr
			//
		} else {
			// 见鬼
			continue
		}
	}
}
